package com.yl.chainStore.control.warehouse

import com.baomidou.mybatisplus.extension.plugins.pagination.Page
import com.yl.chainStore.common.enums.Status
import com.yl.chainStore.control.BaseCtrl
import com.yl.chainStore.entity.warehouse.WarehouseProfitLossOrder
import com.yl.chainStore.pojo.vo.warehouse.WarehouseProfitLossOrderSelectVo
import com.yl.chainStore.services.IWebCompanyUserService
import com.yl.chainStore.services.warehouse.IWarehouseProfitLossOrderService
import com.yl.chainStore.services.warehouse.IWarehouseService
import com.yl.common.ErrorCode
import com.yl.common.control.ResponseBody
import com.yl.common.control.returnError
import com.yl.common.control.returnSuccess
import com.yl.common.getContext
import com.yl.users.common.annotations.PermsCode
import org.springframework.transaction.annotation.Transactional
import org.springframework.transaction.interceptor.TransactionAspectSupport
import org.springframework.web.bind.annotation.*

/**
 * 损益单
 */
@RestController
@RequestMapping("warehouse/plOrder")
open class WarehouseProfitLossOrderController (
	private val iWarehouseProfitLossOrderService: IWarehouseProfitLossOrderService,
	private val iWarehouseService: IWarehouseService,
	private val iWebCompanyUserService: IWebCompanyUserService
		):BaseCtrl() {

	/**
	 * 损益单分页列表
	 */
	@PostMapping("orderPage")
	@PermsCode("warehouse:plOrder:orderPage")
	@Transactional
	open fun orderPage(@RequestBody vo:WarehouseProfitLossOrderSelectVo ): ResponseBody {

		val page = Page<WarehouseProfitLossOrder>(vo.current, vo.size)
		return returnSuccess(
			iWarehouseService.profitLossPage(page, vo)
		)
	}

	/**
	 * 损益明细
	 */
	@GetMapping("orderDetail/{id}")
	@PermsCode("warehouse:plOrder:orderDetail")
	@Transactional
	open fun orderDetail(@PathVariable id: Long): ResponseBody {
		val order = iWarehouseProfitLossOrderService.getOrder(id)
		if(order != null){
			order.details = iWarehouseProfitLossOrderService.getOrderDetail(id)
		}
		return returnSuccess(order)
	}

	/**
	 * 暂存
	 */
	@PostMapping("staging")
	@Transactional(rollbackFor = [Exception::class])
	open fun staging(@RequestBody order: WarehouseProfitLossOrder):ResponseBody{
		if(order.id != 0L){
			//如果有草稿，删除之前的草稿，新增一个草稿
			iWarehouseProfitLossOrderService.delOrder(order.id)
		}
		order.id = 0L
		val res = iWebCompanyUserService.stagingPlOrder(order)
		if (res.code != ErrorCode.SUCCESS.code) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly()
			return res
		}
		if(order.details != null){
			for (detail in order.details!!) {
				detail.orderId = order.id
				detail.status = Status.STAGING
				iWarehouseProfitLossOrderService.addDetail(detail)
			}
		}
		return returnSuccess()
	}

	/**
	 * 取出暂存
	 */
	@GetMapping("getStaging")
	@Transactional
	open fun getStaging():ResponseBody{
		val stagingInOrder = iWebCompanyUserService.getStagingPlOrder(getContext().userId, getContext().subCompanyId)
		if(stagingInOrder != null){
			stagingInOrder.details = iWarehouseProfitLossOrderService.getOrderDetail(stagingInOrder.id)
		}
		return returnSuccess(stagingInOrder)
	}

	/**
	 * 申请
	 */
	@PostMapping("addOrder")
	@PermsCode("warehouse:plOrder:addOrder")
	@Transactional(rollbackFor = [Exception::class])
	open fun addOrder(@RequestBody order: WarehouseProfitLossOrder): ResponseBody {
		if(order.id != 0L){
			//如果有草稿，删除之前的草稿，
			iWarehouseProfitLossOrderService.delOrder(order.id)
		}
		order.id = 0L
		val res = iWarehouseService.addProfitLossOrder(order)
		if (res.code != ErrorCode.SUCCESS.code) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly()
			return res
		}
		var i = 1
		for (detail in order.details!!) {
			if (detail.goodCount == 0) {
				return returnError(ErrorCode.DATA_SAVE_FAILED, "第" + i + "行物品错误：请输入物品数量")
			}
			detail.orderId = order.id
			detail.status = Status.WAIT_AUDIT
			val addDetail = iWarehouseProfitLossOrderService.addDetail(detail)
			if (addDetail.code != ErrorCode.SUCCESS.code) {
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly()
				return returnError(ErrorCode.DATA_SAVE_FAILED, "第" + i + "行物品错误：" + addDetail.msg)
			}
			i++
		}
		return returnSuccess()
	}

	/**
	 * 审核通过
	 */
	@PostMapping("performOrder/{id}")
	@Transactional(rollbackFor = [Exception::class])
	@PermsCode("warehouse:plOrder:audit")
	open fun performOrder(@PathVariable id: Long): ResponseBody {
		val completeInOrder = iWarehouseProfitLossOrderService.completeOrder(id)
		if (completeInOrder.code != ErrorCode.SUCCESS.code) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly()
		}
		return completeInOrder
	}


	/**
	 * 审核不通过
	 */
	@PostMapping("noPassOrder/{id}")
	@Transactional(rollbackFor = [Exception::class])
	@PermsCode("warehouse:plOrder:audit")
	open fun noPassOrder(@PathVariable id: Long): ResponseBody {
		val completeInOrder = iWarehouseProfitLossOrderService.noPassOrder(id)
		if (completeInOrder.code != ErrorCode.SUCCESS.code) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly()
		}
		return completeInOrder
	}

	/**
	 * 取消订单（作废）
	 */
	@PostMapping("cancelOrder/{id}")
	@Transactional(rollbackFor = [Exception::class])
	@PermsCode("warehouse:plOrder:cancel")
	open fun cancelOrder(@PathVariable id: Long): ResponseBody {
		val completeInOrder = iWarehouseProfitLossOrderService.cancelOrder(id)
		if (completeInOrder.code != ErrorCode.SUCCESS.code) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly()
		}
		return completeInOrder
	}
}
